package com.zhihuishu.micro.course.openapi.online.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.zhihuishu.micro.course.dto.CourseCategoryDto;
import com.zhihuishu.micro.course.dto.CourseTagDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.openapi.online.CourseCategoryOpenService;
import com.zhihuishu.micro.course.openapi.online.dto.CategoryOpenDto;
import com.zhihuishu.micro.course.openapi.online.dto.CourseCategoryOpenDto;
import com.zhihuishu.micro.course.openapi.online.dto.CourseTagOpenDto;
import com.zhihuishu.micro.course.service.CategoryService;
import com.zhihuishu.micro.course.service.CourseService;
import com.zhihuishu.micro.course.service.TagService;
import com.zhihuishu.myuni.openapi.course.ICourseRemoteService;
import com.zhihuishu.myuni.openapi.course.dto.CourseWebDto;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

@Service("courseCategoryOpenService")
public class CourseCategoryOpenServiceImpl implements CourseCategoryOpenService {

	@Resource
	private CategoryService categoryService ;
	@Resource
	private CourseService courseService;
	@Resource
	private TagService tagService ;
	
	@Resource
	private ICourseRemoteService myuniCourseRemoteService ;
	
	@Override
	public RemoteResult<?> queryCategoriesByParentId(int parentId) throws RemoteException {
		RemoteResult<ArrayList<CategoryOpenDto>> result = new RemoteResult<ArrayList<CategoryOpenDto>>() ;
		try {
			ArrayList<CategoryOpenDto> list = (ArrayList<CategoryOpenDto>) BeanHelper
					.transTo(categoryService.list(parentId), CategoryOpenDto.class);
			if(!CollectionUtils.isEmpty(list)) {
				result.setResult(list);
			}
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("根据父级分类ID查询子分类列表出错!") ;
		}
		
		return result ;
	}
	
	@Override
	public RemoteResult<?> queryCategoriesByCourseId(long courseId) throws RemoteException {
		RemoteResult<ArrayList<CourseCategoryOpenDto>> result = new RemoteResult<ArrayList<CourseCategoryOpenDto>>() ;
		try {
			List<CourseCategoryDto> list = categoryService.listByCourse(courseId) ;
			if(!CollectionUtils.isEmpty(list)) {
				ArrayList<CourseCategoryOpenDto> target = new ArrayList<CourseCategoryOpenDto>() ; 
				for(CourseCategoryDto ccd : list) {
					CourseCategoryOpenDto ccod = new CourseCategoryOpenDto() ;
					ccod.setId(ccd.getId());
					ccod.setCourseId(ccd.getCourseId());
					ccod.setFirst(BeanHelper.transTo(ccd.getFirst(), CategoryOpenDto.class));
					ccod.setSecond(BeanHelper.transTo(ccd.getSecond(), CategoryOpenDto.class));
					ccod.setThird(BeanHelper.transTo(ccd.getThird(), CategoryOpenDto.class));
					target.add(ccod) ;
				}
				result.setResult(target);
			}
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("根据课程ID查询课程分类列表出错!") ;
		}
		
		return result ;
	}
	
	@Override
	public RemoteResult<Integer> createCourseCategory(
			CourseCategoryOpenDto courseCategory) throws RemoteException {
		RemoteResult<Integer> result = new RemoteResult<Integer>() ;
		// 参数检查
		if(courseCategory == null || courseCategory.getCourseId() == null
				|| courseCategory.getFirstId() == null 
				|| courseCategory.getSecondId() == null 
				|| courseCategory.getThirdId() == null) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}

		// 执行保存
		try {
			CourseCategoryDto cc = new CourseCategoryDto() ;
			cc.setCourseId(courseCategory.getCourseId());
			cc.setFirstId(courseCategory.getFirstId());
			cc.setSecondId(courseCategory.getSecondId());
			cc.setThirdId(courseCategory.getThirdId());
			Integer courseCategoryId = categoryService.saveCourseCategory(cc) ;
			LoggerTemplateUtil.saveLogger(
					String.format("创建课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d", courseCategory.getCourseId(),courseCategory.getFirstId(),
							courseCategory.getSecondId(),courseCategory.getThirdId()), 
					0L, LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
			if(courseCategoryId == null) {
				result.setSuccess(false);
				result.setErrorCode(1);
			} result.setResult(courseCategoryId);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("创建课程分类执行出错!") ;
		}
		
		return result ;
	}

	@Override
	public RemoteResult<Void> updateCourseCategory(
			CourseCategoryOpenDto courseCategory) throws RemoteException {
		RemoteResult<Void> result = new RemoteResult<Void>() ;
		// 参数检查
		if(courseCategory == null || courseCategory.getId() == null
				|| (courseCategory.getFirstId() == null 
				&& courseCategory.getSecondId() == null 
				&& courseCategory.getThirdId() == null)) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}

		try {
			// 执行本地更新
			CourseCategoryDto cc = new CourseCategoryDto() ;
			cc.setId(courseCategory.getId());
			cc.setCourseId(courseCategory.getCourseId());
			cc.setFirstId(courseCategory.getFirstId());
			cc.setSecondId(courseCategory.getSecondId());
			cc.setThirdId(courseCategory.getThirdId());
			categoryService.updateCourseCategory(cc) ;
			LoggerTemplateUtil.saveLogger(
					String.format("更新课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d", courseCategory.getCourseId(),courseCategory.getFirstId(),
							courseCategory.getSecondId(),courseCategory.getThirdId()), 
					0L, LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
			// 执行远程更新
			Long myuniCourseId=courseService.getMyuniCourseId(cc.getCourseId());
			if (myuniCourseId!=null) {
				CourseWebDto cwd = new CourseWebDto() ;
				cwd.setOnlineCourseId(cc.getCourseId().intValue());
				cwd.setCateOne(cc.getFirstId());
				cwd.setCateTwo(cc.getSecondId());
				cwd.setCategoryId(cc.getThirdId());
				myuniCourseRemoteService.update(cwd, -9L);
				LoggerTemplateUtil.saveLogger(
						String.format("远程更新myuni课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d", courseCategory.getCourseId(),courseCategory.getFirstId(),
								courseCategory.getSecondId(),courseCategory.getThirdId()), 
						0L, LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
			}
			
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("创建课程分类执行出错!") ;
		}
		
		return result ;
	}

	@Override
	public RemoteResult<?> listByCourseId(long courseId) throws RemoteException {
		RemoteResult<ArrayList<CourseTagOpenDto>> result = new RemoteResult<ArrayList<CourseTagOpenDto>>() ;
		try {
			List<CourseTagDto> list = tagService.listByCourseId(courseId) ;
			fillTagResult(result ,list) ;
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("创建课程标签执行出错!") ;
		}
		
		return result ;
	}

	@Override
	public RemoteResult<ArrayList<CourseTagOpenDto>> saveCourseTag(long courseId, String... tags)
			throws RemoteException {
		RemoteResult<ArrayList<CourseTagOpenDto>> result = new RemoteResult<ArrayList<CourseTagOpenDto>>() ;
		// 参数检查
		if(ArrayUtils.isEmpty(tags)) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}

		try {
			List<CourseTagDto> list = tagService.saveCourseTag(courseId, tags);
			StringBuffer tagIds = new StringBuffer();
			for (CourseTagDto dto : list) {
				tagIds.append(dto.getTagId()+",");
			}
			LoggerTemplateUtil.saveLogger(String.format("创建课程标签,courseId=%d,tagsIds=%s", courseId, tagIds.toString()), 
					0L, LoggerCollectionEnum.courseCollection, courseId);
			fillTagResult(result ,list) ;
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("创建课程标签执行出错!") ;
		}
		
		return result ;
	}
	
	/**
	 * 填充标签查询结果集
	 * @param result
	 * @param list
	 */
	private void fillTagResult(final RemoteResult<ArrayList<CourseTagOpenDto>> result ,final List<CourseTagDto> list) {
		if(CollectionUtils.isEmpty(list)) return ;
		result.setResult((ArrayList<CourseTagOpenDto>) BeanHelper.transTo(list, CourseTagOpenDto.class));
	}

	@Override
	public RemoteResult<Void> deleteCourseTag(long courseId, int... tagIds)
			throws RemoteException {
		RemoteResult<Void> result = new RemoteResult<Void>() ;
		// 参数检查
		if(ArrayUtils.isEmpty(tagIds)) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}

		try {
			tagService.deleteCourseTag(courseId, tagIds);
			StringBuffer tagIdstr = new StringBuffer();
			for (int tagId : tagIds) {
				tagIdstr.append(tagId+",");
			}
			LoggerTemplateUtil.saveLogger(String.format("删除课程标签,courseId=%d,tagsIds=%s", courseId, tagIdstr.toString()), 
					0L, LoggerCollectionEnum.courseCollection, courseId);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("删除课程标签执行出错!") ;
		}
		
		return result ;
	}

	@Override
	public RemoteResult<Void> deleteCourseCategoryById(Integer id) {
		RemoteResult<Void> remoteResult =new RemoteResult<Void>();
		try {
			Assert.notNull(id, "删除课程分类标签id不能为空");
			categoryService.deleteById(id);
			LoggerTemplateUtil.saveLogger(String.format("删除课程分类标签,categoryId=%d", id), 0L, LoggerCollectionEnum.courseCollection);
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			remoteResult.setExceptionStack(e);
		}
		return remoteResult;
	}

}
